package com.base.lib.utils.jpush;

import android.app.Notification;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.base.lib.R;

import java.util.LinkedHashSet;
import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


public class JPushSetUitl {
    private static final String TAG = "JPush";
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;
    public static boolean isForeground = false;
    static JPushSetUitl jPushSetUitl;
    Context context;
    /**
     * 是否初始化成功
     */
    private boolean isInitPushData = false;
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    isInitPushData = !TextUtils.isEmpty(alias);
                    logs = "设置标签和别名成功";
                    Log.i(TAG, logs);
                    break;
                case 6002:
                    isInitPushData = false;
                    logs = "由于超时未能设定别名和标签。60S后再试一次。";
                    Log.i(TAG, logs);
                    if (JpushUtil.isConnected(context)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 6);
                    } else {
                        Log.i(TAG, "没有网络");
                    }
                    break;

                default:
                    logs = "失败,错误代码 = " + code;
                    Log.e(TAG, logs);
            }

//			JUtil.showToast(logs, context);
        }

    };
    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "设置标签和别名成功";
                    isInitPushData = true;
                    Log.i(TAG, logs);
                    break;

                case 6002:
                    logs = "由于超时未能设定别名和标签。60S后再试一次。";
                    isInitPushData = false;
                    Log.i(TAG, logs);
                    if (JpushUtil.isConnected(context)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        Log.i(TAG, "没有网络");
                    }
                    break;

                default:
                    logs = "失败,错误代码 = " + code;
                    Log.e(TAG, logs);
            }

//			JUtil.showToast(logs, context);
        }

    };
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "在处理程序设置别名:" + msg.obj);
                    JPushInterface.setAliasAndTags(context, (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    Log.d(TAG, "设置标记处理程序.");
                    JPushInterface.setAliasAndTags(context, null, (Set<String>) msg.obj, mTagsCallback);
                    break;

                default:
                    Log.i(TAG, "未处理的 msg - " + msg.what);
            }
        }
    };

    public JPushSetUitl(Context context) {
        this.context = context;
        String udid = JpushUtil.getImei(context, "");
        String appKey = JpushUtil.getAppKey(context);
        String packageName = context.getPackageName();
        String versionName = JpushUtil.GetVersion(context);
        Log.i(TAG, "IMEI: " + udid + "\nAppKey: " + appKey + "\nPackageName: " + packageName + "\nVersion: " + versionName);

        // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
//		JPushInterface.init(context);
//		registerMessageReceiver();  // used for receive msg

    }

    public static JPushSetUitl getPushSetUitl(Context context) {
        if (jPushSetUitl == null && context != null) {
            jPushSetUitl = new JPushSetUitl(context);
        }
        return jPushSetUitl;
    }

    public boolean isInitPushData() {
        return isInitPushData;
    }

    public void setInitPushData(boolean isInitPushData) {
        this.isInitPushData = isInitPushData;
    }

    public void onPause() {
        JPushInterface.onPause(context);
    }

    public void onResume() {
        JPushInterface.onResume(context);

    }

    public void onDestroy() {/*
		if(mMessageReceiver != null){
			try {
				context.unregisterReceiver(mMessageReceiver);
				mMessageReceiver=null;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.e(TAG, "unregisterReceiver");
		}
	*/
    }

    public void stopPush() {
        JPushInterface.stopPush(context);
        setInitPushData(false);
        JPushInterface.cleanTags(context, MSG_SET_TAGS);
        JPushInterface.deleteAlias(context, MSG_SET_ALIAS);
    }

    /**
     * Tag为大小写字母，数字，下划线,中文， 多个用以逗号分隔
     *
     * @param tag
     */
    public void setTag(String tag) {
        tag = tag.replace("-", "_");
        // 检查 tag 的有效性
        if (TextUtils.isEmpty(tag)) {
            Toast.makeText(context, "tag不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // ","隔开的多个 转换成 Set
        String[] sArray = tag.split(",");
        Set<String> tagSet = new LinkedHashSet<String>();
        for (String sTagItme : sArray) {
            if (!JpushUtil.isValidTagAndAlias(sTagItme)) {
                Toast.makeText(context, "格式不对", Toast.LENGTH_SHORT).show();
                return;
            }
            tagSet.add(sTagItme);
        }

        //调用JPush API设置Tag
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_TAGS, tagSet));

    }

    /**
     * Alias为大小写字母，数字，下划线
     *
     * @param alias
     */
    public void setAlias(String alias) {
        alias = alias.replace("-", "_");
        if (TextUtils.isEmpty(alias)) {
//			Toast.makeText(context,"alias不能为空", Toast.LENGTH_SHORT).show();
            //alias为空，清空之前的配置
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
            return;
        }
        if (!JpushUtil.isValidTagAndAlias(alias)) {
            Toast.makeText(context, "格式不对", Toast.LENGTH_SHORT).show();
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    /**
     * 设置通知提示方式 - 基础属性
     */
    public void setStyleBasic() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(context);
        builder.statusBarDrawable = R.mipmap.ic_launcher;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;  //设置为点击后自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND;  //设置为铃声（ Notification.DEFAULT_SOUND）或者震动（ Notification.DEFAULT_VIBRATE）
        JPushInterface.setPushNotificationBuilder(1, builder);
//		Toast.makeText(context, "Basic Builder - 1", Toast.LENGTH_SHORT).show();
    }

    /**
     * 设置通知栏样式 - 定义通知栏Layout
     */
    private void setStyleCustom() {/*
		CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(context,R.layout.customer_notitfication_layout,R.id.icon, R.id.title, R.id.text);
		builder.layoutIconDrawable = R.drawable.ic_launcher;
		builder.developerArg0 = "developerArg2";
		JPushInterface.setPushNotificationBuilder(2, builder);
		Toast.makeText(context,"Custom Builder - 2", Toast.LENGTH_SHORT).show();
	 */
    }


}